package constant.milk.cashbook.auto;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.asset.MemoActivity;
import constant.milk.cashbook.asset.MoneyActivity;
import constant.milk.cashbook.bean.AutoMainData;
import constant.milk.cashbook.bean.BankData;
import constant.milk.cashbook.bean.CategoryMainData;
import constant.milk.cashbook.bean.CategorySubData;
import constant.milk.cashbook.bean.CheckData;
import constant.milk.cashbook.bean.CreditData;
import constant.milk.cashbook.bean.GiftData;
import constant.milk.cashbook.bean.PhoneData;
import constant.milk.cashbook.bean.RealData;
import constant.milk.cashbook.category.CategoryMainListActivity;
import constant.milk.cashbook.category.CategorySubListActivity;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbDeleteQuery;
import constant.milk.cashbook.database.DbUpdateQuery;
import constant.milk.cashbook.insert.AssetChoiceActivity;
import constant.milk.cashbook.insert.AssetListActivity;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkManager;
import constant.milk.cashbook.util.MilkUtil;
import constant.milk.cashbook.util.TimeActivity;

public class AutoInInfoActivity extends SuperActivity
{
	public static final String AUTO_IN_ID = "AUTO_IN_ID";
	
	public static final int ASSET_CHOICE_REQUEST_CODE = 0;
	public static final int ASSET_LIST_REQUEST_CODE = 1;
	public static final int CATEGORY_MAIN_REQUEST_CODE = 2;
	public static final int CATEGORY_SUB_REQUEST_CODE = 3;
	public static final int MONTH_REQUEST_CODE = 4;
	public static final int WEEKDAY_REQUEST_CODE = 5;
	public static final int TIME_REQUEST_CODE = 6;
	public static final int MONEY_REQUEST_CODE = 7;
	public static final int MEMO_REQUEST_CODE = 8;
	
	private View autoMonthView;
	private View autoWeekdayView;
	
	private View assetView;
	private TextView assetTextView;
	
	private View assetNameView;
	private TextView assetNameTextView;
	
	private View mainCategoryView;
	private TextView mainCategoryTextView;
	
	private View subCategoryView;
	private TextView subCategoryTextView;
	
	private View dateView;
	private TextView dateTextView;
	
	private View weekdayView;
	private TextView weekdayTextView;
	
	private View timeView;
	private TextView timeTextView;
	
	private View moneyView;
	private TextView moneyTextView;
	
	private View memoView;
	private TextView memoTextView;
	
	private Button deleteButton;
	private Button updateButton;
	
	private ArrayList<String> assetNameList;
	private ArrayList<String> categoryMainList;
	private ArrayList<String> categorySubList;
	
	private DBSelectQuery select;
	
	private String am_pm;
	private String hour;
	private String minute;
	
	private MilkManager assetManager;
	
	private int monthWeekdayFlag;
	
	private AutoMainData data;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.auto_info_activity);
		
		setTitle("고정수입정보");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		autoMonthView = findViewById(R.id.autoInfoAutoMonthView);
		autoWeekdayView = findViewById(R.id.autoInfoAutoWeekdayView);
		
		assetView = findViewById(R.id.autoInfoAssetView);
		assetTextView = (TextView) findViewById(R.id.autoInfoAssetTextView);
		
		assetNameView = findViewById(R.id.autoInfoAssetNameView);
		assetNameTextView = (TextView) findViewById(R.id.autoInfoAssetNameTextView);
		
		mainCategoryView = findViewById(R.id.autoInfoMainCategoryView);
		mainCategoryTextView = (TextView) findViewById(R.id.autoInfoMainCategoryTextView);
		
		subCategoryView = findViewById(R.id.autoInfoSubCategoryView);
		subCategoryTextView = (TextView) findViewById(R.id.autoInfoSubCategoryTextView);
		
		dateView = findViewById(R.id.autoInfoDateView);
		dateTextView = (TextView) findViewById(R.id.autoInfoDateTextView);
		
		weekdayView = findViewById(R.id.autoInfoWeekdayView);
		weekdayTextView = (TextView) findViewById(R.id.autoInfoWeekdayTextView);
		
		timeView = findViewById(R.id.autoInfoTimeView);
		timeTextView = (TextView) findViewById(R.id.autoInfoTimeTextView);
		
		moneyView = findViewById(R.id.autoInfoMoneyView);
		moneyTextView = (TextView) findViewById(R.id.autoInfoMoneyTextView);
		
		memoView = findViewById(R.id.autoInfoMemoView);
		memoTextView = (TextView) findViewById(R.id.autoInfoMemoTextView);
		
		deleteButton = (Button) findViewById(R.id.deleteButton);
		updateButton = (Button) findViewById(R.id.updateButton);
	}

	@Override
	protected void setOnClick()
	{
		assetView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, AssetChoiceActivity.class);
				intent.putExtra(AssetChoiceActivity.INSERT_TYPE, AssetChoiceActivity.IN);
				intent.putExtra(AssetChoiceActivity.ASSET_CHOICE_DATA, assetTextView.getText().toString());
				startActivityForResult(intent, ASSET_CHOICE_REQUEST_CODE);
			}
		});
		
		assetNameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startAssetNameList();
			}
		});
		
		mainCategoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startCategoryMainList();
			}
		});
		
		subCategoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startCategorySubList();
			}
		});
		
		dateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startMonth();
			}
		});
		
		weekdayView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startWeekday();
			}
		});
		
		timeView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startTime();
			}
		});
		
		moneyView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startMoney();
			}
		});
		
		memoView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startMemo();
			}
		});
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (setDeleteData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 삭제에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (!checkInsert())
				{
					return;
				}
				
				if (setUpdateData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 수정에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		assetManager = new MilkManager(superContext, superDb);
		select = new DBSelectQuery(superContext, superDb);
		
		Intent intent = getIntent();
		String id = intent.getStringExtra(AUTO_IN_ID);
		
		data = select.getAutoId(id);
		
		if (data.getMonthweekday().equals("0"))
		{
			setMonthSelect();
			
			dateTextView.setText(data.getAutodate());
		}
		else if (data.getMonthweekday().equals("1"))
		{
			setWeekdaySelect();
			
			weekdayTextView.setText(assetManager.getWeekdayStr(data.getAutodate()));
		}
		
		assetTextView.setText(assetManager.getAssetId(data.getAsset()));
		
		setAssetNameData(assetManager.getAssetId(data.getAsset()));
		
		assetNameTextView.setText(data.getName());
		
		setCategoryMain();
		
		setCategorySub();
		
		mainCategoryTextView.setText(data.getMaincategory());
		
		subCategoryTextView.setText(data.getSubcategory());
		
		if (Integer.parseInt(data.getAmpm()) == Calendar.AM)
		{
			am_pm = "AM";
		}
		else
		{
			am_pm = "PM";
		}
		
		if (Integer.parseInt(data.getTimehour()) < 10)
		{
			hour = "0" + data.getTimehour();
		}
		else
		{
			hour = data.getTimehour() + "";
		}
		
		if (Integer.parseInt(data.getTimeminute()) < 10)
		{
			minute = "0" + data.getTimeminute();
		}
		else
		{
			minute = data.getTimeminute() + "";
		}
		
		setTimeView();
		
		moneyTextView.setText(MilkUtil.getWon(data.getMoney()));
		
		memoTextView.setText(data.getMemo());
	}
	
	private void setMonthSelect()
	{
		autoMonthView.setVisibility(View.VISIBLE);
		autoWeekdayView.setVisibility(View.GONE);
		
		dateView.setVisibility(View.VISIBLE);
		weekdayView.setVisibility(View.GONE);
		
		monthWeekdayFlag = AutoActivity.MONTH;
	}
	
	private void setWeekdaySelect()
	{
		autoMonthView.setVisibility(View.GONE);
		autoWeekdayView.setVisibility(View.VISIBLE);
		
		dateView.setVisibility(View.GONE);
		weekdayView.setVisibility(View.VISIBLE);
		
		monthWeekdayFlag = AutoActivity.WEEKDAY;
	}
	
	private boolean checkInsert()
	{
		if (assetNameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "자산을 추가해 주세요.");
			return false;
		}
		
		if (mainCategoryTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "메인 카테고리를 추가해 주세요.");
			return false;
		}
		
		if (subCategoryTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "서브 카테고리를 추가해 주세요.");
			return false;
		}
		
		if (moneyTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "금액을 정확히 입력해 주세요.");
			return false;
		}
		
		if (memoTextView.getText().equals(""))
		{
			MilkUtil.showToast(superContext, "내용을 입력해 주세요.");
			return false;
		}
		
		return true;
	}
	
	private boolean setDeleteData()
	{
		DbDeleteQuery query = null;
		try
		{
			query = new DbDeleteQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			query.setAutoMainDelete(data.getId());
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setUpdateData()
	{
		DbUpdateQuery query = null;
		
		try
		{
			query = new DbUpdateQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("type", "1");
			
			map.put("kind", "0");
			
			map.put("asset", assetManager.getAssetStr(assetTextView.getText().toString()));
			map.put("name", assetNameTextView.getText().toString());
			map.put("maincategory", mainCategoryTextView.getText().toString());
			map.put("subcategory", subCategoryTextView.getText().toString());
			map.put("ampm", MilkUtil.getAmPm(am_pm));
			map.put("timehour", hour);
			map.put("timeminute", minute);
			map.put("money", MilkUtil.getCommaDel(moneyTextView.getText().toString()));
			map.put("memo", memoTextView.getText().toString());
			
			if (monthWeekdayFlag == 0)
			{
				map.put("monthweekday", "0");
				map.put("autodate", dateTextView.getText().toString());
			}
			else if (monthWeekdayFlag == 1)
			{
				map.put("monthweekday", "1");
				map.put("autodate", assetManager.getWeekdayInt(weekdayTextView.getText().toString()));
			}
			
			query.setAutoMainUpdate(map, data.getId());
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == ASSET_CHOICE_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetChoiceActivity.ASSET_CHOICE_DATA);
			assetTextView.setText(str);
			
			setAssetNameData(str);
			
		}
		else if (requestCode == ASSET_LIST_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetListActivity.ASSET_NAME_DATA);
			assetNameTextView.setText(str);
			
		}
		else if (requestCode == CATEGORY_MAIN_REQUEST_CODE)
		{
			String str = data.getStringExtra(CategoryMainListActivity.CATEGORY_MAIN_NAME_DATA);
			mainCategoryTextView.setText(str);
			
			setCategorySub();
			
		}
		else if (requestCode == CATEGORY_SUB_REQUEST_CODE)
		{
			String str = data.getStringExtra(CategorySubListActivity.CATEGORY_SUB_NAME_DATA);
			subCategoryTextView.setText(str);
			
		}
		else if (requestCode == MONTH_REQUEST_CODE)
		{
			String str = data.getStringExtra(AutoMonthActivity.MONTH_DATA);
			dateTextView.setText(str);
		}
		else if (requestCode == WEEKDAY_REQUEST_CODE)
		{
			String str = data.getStringExtra(AutoWeekdayActivity.WEEKDAY_DATA);
			
			if (str.equals("일"))
			{
				weekdayTextView.setTextColor(Color.RED);
			}
			else if (str.equals("토"))
			{
				weekdayTextView.setTextColor(Color.BLUE);
			}
			else
			{
				weekdayTextView.setTextColor(TEXT_COLOR);
			}
			
			weekdayTextView.setText(str);
		}
		else if (requestCode == TIME_REQUEST_CODE)
		{
			am_pm = data.getStringExtra(TimeActivity.TIME_AM_PM_DATA);
			hour = data.getStringExtra(TimeActivity.TIME_HOUR_DATA);
			minute = data.getStringExtra(TimeActivity.TIME_MINUTE_DATA);
			setTimeView();
			
		}
		else if (requestCode == MONEY_REQUEST_CODE)
		{
			String money = data.getStringExtra(MoneyActivity.MONEY_DATA);
			
			moneyTextView.setText(money);
		}
		else if (requestCode == MEMO_REQUEST_CODE)
		{
			String memo = data.getStringExtra(MemoActivity.MEMO_DATA);
			
			memoTextView.setText(memo);
		}
	}
	
	private void startAssetNameList()
	{
		Intent intent = new Intent(superContext, AssetListActivity.class);
		intent.putExtra(AssetListActivity.ASSET_NAME_DATA, assetNameTextView.getText().toString());
		intent.putExtra(AssetListActivity.ASSET_TYPE_DATA, assetTextView.getText().toString());
		startActivityForResult(intent, ASSET_LIST_REQUEST_CODE);
	}
	
	private void startCategoryMainList()
	{
		Intent intent = new Intent(superContext, CategoryMainListActivity.class);
		intent.putExtra(CategoryMainListActivity.CATEGORY_MAIN_NAME_DATA, mainCategoryTextView.getText().toString());
		intent.putExtra(CategoryMainListActivity.CATEGORY_MAIN_LIST_DATA, categoryMainList);
		startActivityForResult(intent, CATEGORY_MAIN_REQUEST_CODE);
	}
	
	private void startCategorySubList()
	{
		Intent intent = new Intent(superContext, CategorySubListActivity.class);
		intent.putExtra(CategorySubListActivity.CATEGORY_MAIN_NAME_DATA, mainCategoryTextView.getText().toString());
		intent.putExtra(CategorySubListActivity.CATEGORY_SUB_NAME_DATA, subCategoryTextView.getText().toString());
		intent.putExtra(CategorySubListActivity.CATEGORY_SUB_LIST_DATA, categorySubList);
		startActivityForResult(intent, CATEGORY_SUB_REQUEST_CODE);
	}
	
	private void startMonth()
	{
		Intent intent = new Intent(superContext, AutoMonthActivity.class);
		intent.putExtra(AutoMonthActivity.MONTH_DATA, dateTextView.getText().toString());
		startActivityForResult(intent, MONTH_REQUEST_CODE);
	}
	
	private void startWeekday()
	{
		Intent intent = new Intent(superContext, AutoWeekdayActivity.class);
		intent.putExtra(AutoWeekdayActivity.WEEKDAY_DATA, weekdayTextView.getText().toString());
		startActivityForResult(intent, WEEKDAY_REQUEST_CODE);
	}
	
	private void startTime()
	{
		Intent intent = new Intent(superContext, TimeActivity.class);
		intent.putExtra(TimeActivity.TIME_AM_PM_DATA, am_pm);
		intent.putExtra(TimeActivity.TIME_HOUR_DATA, hour);
		intent.putExtra(TimeActivity.TIME_MINUTE_DATA, minute);
		startActivityForResult(intent, TIME_REQUEST_CODE);
	}
	
	private void startMoney()
	{
		Intent intent = new Intent(superContext, MoneyActivity.class);
		intent.putExtra(MoneyActivity.MONEY_DATA, moneyTextView.getText().toString());
		startActivityForResult(intent, MONEY_REQUEST_CODE);
	}
	
	private void startMemo()
	{
		Intent intent = new Intent(superContext, MemoActivity.class);
		intent.putExtra(MemoActivity.MEMO_DATA, memoTextView.getText().toString());
		startActivityForResult(intent, MEMO_REQUEST_CODE);
	}

	private void setAssetNameData(String str)
	{
		DBSelectQuery query = new DBSelectQuery(superContext, superDb);
		
		assetNameList = new ArrayList<String>();
		
		if (str.equals(getString(R.string.realAsset)))
		{
			ArrayList<RealData> list = query.getRealList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("현금을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.bankAsset)))
		{
			ArrayList<BankData> list = query.getBankList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("통장을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.checkCardAsset)))
		{
			ArrayList<CheckData> list = query.getCheckList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("체크카드를 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.creditCardAsset)))
		{
			ArrayList<CreditData> list = query.getCreditList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("신용카드를 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.phoneAsset)))
		{
			ArrayList<PhoneData> list = query.getPhoneList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("핸드폰을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.giftCardAsset)))
		{
			ArrayList<GiftData> list = query.getGiftList();
			
			if (list == null || list.size() < 1)
			{
				assetNameTextView.setText("");
				assetNameTextView.setHint("상품권을 추가해주세요.");
				return;
			}
			
			assetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
	}
	
	private void setCategoryMain()
	{
		ArrayList<CategoryMainData> list = select.getCategoryMainList();
		
		if (list == null || list.size() < 1)
		{
			mainCategoryTextView.setText("");
			mainCategoryTextView.setHint("카테고리를 추가해주세요.");
			return;
		}
		
		mainCategoryTextView.setText(list.get(0).getName());
		
		categoryMainList = new ArrayList<String>();
		
		for (int i = 0; i < list.size(); i++)
		{
			categoryMainList.add(list.get(i).getName());
		}
	}
	
	private void setCategorySub()
	{
		if (mainCategoryTextView.getText().toString().equals(""))
		{
			subCategoryTextView.setText("");
			subCategoryTextView.setHint("카테고리를 추가해주세요.");
			return;
		}
		
		CategoryMainData data = select.getCategoryMainName(mainCategoryTextView.getText().toString());
		
		ArrayList<CategorySubData> list = select.getCategorySubList(data.getId());
		
		if (list == null || list.size() < 1)
		{
			subCategoryTextView.setText("");
			subCategoryTextView.setHint("카테고리를 추가해주세요.");
			return;
		}
		
		subCategoryTextView.setText(list.get(0).getName());
		
		categorySubList = new ArrayList<String>();
		
		for (int i = 0; i < list.size(); i++)
		{
			categorySubList.add(list.get(i).getName());
		}
	}
	
	private void setTimeView()
	{
		timeTextView.setText(MilkUtil.getTime(am_pm, hour, minute));
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_AUTO_IN_INFO);
		startActivity(intent);
	}

}
